from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model

User = get_user_model()


# Create your models here.


class Channel(models.Model):
    # 类型选项
    CHANNE_CHOICES = [
        ('DingDing', '钉钉'),
        ('Email', '邮件'),
    ]
    # 字段定义
    channel_name = models.CharField(
        primary_key=True,
        max_length=20,
        verbose_name='名称'
    )

    author = models.ForeignKey(User, verbose_name=_('Author'), on_delete=models.CASCADE, related_name='channel_auther'
                               )

    channel_type = models.CharField(
        max_length=20,
        choices=CHANNE_CHOICES,
        verbose_name='类型'
    )
    channel_addr = models.CharField(
        max_length=200,
        verbose_name='地址'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )

    def __str__(self):
        return f"{self.channel_type} ({self.channel_addr})"

    class Meta:
        verbose_name = '任务'
        verbose_name_plural = '任务'
        ordering = ['-created_at']  # 默认按创建时间倒序


class Task(models.Model):

    # 状态选项
    STATUS_COMPLETED = 'completed'
    STATUS_IN_PROGRESS = 'in_progress'
    STATUS_PENDING = 'pending'
    STATUS_CHOICES = [
        (STATUS_COMPLETED, '完成'),
        (STATUS_IN_PROGRESS, '进行中'),
        (STATUS_PENDING, '待运行'),
    ]

    task_id = models.IntegerField(primary_key=True)
    author = models.ForeignKey(User, verbose_name=_('Author'), on_delete=models.CASCADE, related_name='task_auth')

    channel = models.ForeignKey(
        Channel,
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        to_field='channel_name'
    )
    title = models.CharField(
        max_length=200,
        verbose_name='标题'
    )
    detail = models.TextField(
        verbose_name='详情'
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default=STATUS_IN_PROGRESS,
        verbose_name='状态'
    )
    time = models.DateTimeField(
        verbose_name='时间'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )

    def __str__(self):
        return f"{self.title} ({self.get_status_display()})"

    class Meta:
        verbose_name = '任务'
        verbose_name_plural = '任务'
        ordering = ['-created_at']  # 默认按创建时间倒序
